<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入姓名/手机号/案件名称"
            clearable
            size="small"
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAddCustomer"
            >新增客户</el-button
          >
        </el-form-item>
      </el-form>

      <el-table
        :data="customerList"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column type="expand" align="center">
          <template slot-scope="scope">
            <el-row>
              <el-col :span="2"
                ><div class="lawyer-title">案由/罪名:</div></el-col
              >
              <el-col :span="22">
                <div class="lawyer-title">{{ scope.row.case_name }}</div>
              </el-col>
            </el-row>
            <el-row v-if="scope.row.lawyers.length > 0">
              <el-col :span="2"
                ><div class="lawyer-title">负责律师:</div></el-col
              >
              <el-col :span="22">
                <el-tooltip
                  effect="dark"
                  v-for="(item, index) in scope.row.lawyers"
                  :key="item.id"
                  :content="item.post_name"
                  placement="top-start"
                >
                  <el-tag
                    effect="plain"
                    :key="item.id"
                    closable
                    type="success"
                    @close="delLawyer(scope.row, index, item)"
                  >
                    {{ item.lawyer }}
                  </el-tag>
                </el-tooltip>
              </el-col>
            </el-row>

            <el-table
              :data="scope.row.persons"
              border
              v-if="scope.row.persons.length > 0"
              size="mini"
            >
              <el-table-column align="center" label="姓名" prop="name" />
              <el-table-column align="center" label="性别" prop="gender" />
              <el-table-column
                align="center"
                label="手机号码"
                prop="telephone"
              />
              <el-table-column align="center" label="身份证号" prop="id_card" />
              <el-table-column align="center" label="操作" width="200px">
                <template slot-scope="props">
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    @click="handlePersonEdit(scope.row, props.row)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="handlePersonDelete(scope.row, props)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column
          align="center"
          label="姓名"
          prop="name"
        ></el-table-column>
        <el-table-column
          align="center"
          label="性别"
          prop="gender"
          width="100"
        ></el-table-column>
        <el-table-column
          align="center"
          label="手机号码"
          prop="telephone"
        ></el-table-column>

        <el-table-column
          align="center"
          label="类型"
          prop="cate_name"
        ></el-table-column>
        <el-table-column
          align="center"
          label="助记符"
          width="150"
          prop="help_code"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
            ></el-button>
            <el-button
              type="success"
              size="mini"
              icon="el-icon-user"
              @click="handlePerson(scope.row)"
              >人员</el-button
            >
            <el-button
              type="success"
              size="mini"
              icon="el-icon-user"
              @click="handleLawyer(scope.row)"
              >律师</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getCustomers"
      />
    </el-card>
    <!-- 客户对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? '编辑客户' : '新增客户'"
      width="40%"
    >
      <el-form
        :model="customerForm"
        :rules="customerFormRules"
        ref="customerFormRef"
        label-width="80px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            type="text"
            v-model="customerForm.name"
            placeholder="姓名"
            maxlength="24"
            show-word-limit
            clearable
            @input="getHanzi2Pinyin"
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            v-model="customerForm.gender"
            placeholder="请选择性别"
            clearable
          >
            <el-option
              v-for="item in genders"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="telephone">
          <el-input
            v-model="customerForm.telephone"
            maxlength="11"
            show-word-limit
            placeholder="手机号码"
            clearable
          />
        </el-form-item>
        <el-form-item label="案件名称" prop="case_name">
          <el-input
            v-model="customerForm.case_name"
            placeholder="案件名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="案件类型" prop="case_category">
          <el-select
            v-model="customerForm.case_category"
            placeholder="请选择案件类型"
            clearable
          >
            <el-option
              v-for="item in category"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card">
          <el-input
            v-model="customerForm.id_card"
            maxlength="18"
            show-word-limit
            placeholder="身份证号"
            clearable
          />
        </el-form-item>
        <el-form-item label="助记码" prop="help_code">
          <el-input
            v-model="customerForm.help_code"
            placeholder="助记码"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="SaveCustomer">保存</el-button>
      </div>
    </el-dialog>
    <!-- 案件相关人员对话框 -->
    <el-dialog
      :visible.sync="dlgPersonVisible"
      :title="
        dlgPersonType === 'edit'
          ? '编辑案件相关人员信息'
          : '新增案件相关人员信息'
      "
      width="40%"
    >
      <el-form
        :model="personForm"
        :rules="personFormRules"
        ref="personFormRef"
        label-width="80px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            type="text"
            v-model="personForm.name"
            placeholder="姓名"
            maxlength="24"
            show-word-limit
            clearable
          />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select
            v-model="personForm.gender"
            placeholder="请选择性别"
            clearable
          >
            <el-option
              v-for="item in genders"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="telephone">
          <el-input
            v-model="personForm.telephone"
            maxlength="11"
            show-word-limit
            placeholder="手机号码"
            clearable
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card">
          <el-input
            v-model="personForm.id_card"
            maxlength="18"
            show-word-limit
            placeholder="身份证号"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dlgPersonVisible = false"
          >取消</el-button
        >
        <el-button type="primary" @click="SavePerson(false)">保存</el-button>
        <el-button
          type="primary"
          v-if="dlgPersonType === 'new'"
          @click="SavePerson(true)"
          >保存并新增</el-button
        >
      </div>
    </el-dialog>
    <!-- 负责律师对话框 -->
    <el-dialog
      :visible.sync="dlgLawyerVisible"
      :title="dlgLawyerType === 'edit' ? '编辑负责律师' : '新增负责律师'"
      width="50%"
    >
      <el-row type="flex" justify="end">
        <el-col :xs="20" :sm="16" :md="12" :lg="10" :xl="5">
          <el-button-group style="float: right">
            <el-button
              type="success"
              size="mini"
              icon="el-icon-plus"
              @click="handleLawyerAdd"
              >新增</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-s-promotion"
              size="mini"
              @click="SaveLawyer(false)"
              >保存</el-button
            >
          </el-button-group>
        </el-col>
      </el-row>
      <el-form
        :model="lawyerForm"
        ref="lawyerFormRef"
        :rules="lawyerForm.rules"
      >
        <el-table :data="lawyerForm.params" border size="small">
          <!-- <el-table-column type="selection" align="center"></el-table-column> -->
          <el-table-column label="律师" align="center">
            <template slot-scope="scope">
              <el-form-item
                :prop="'params.' + scope.$index + '.employee'"
                :rules="lawyerForm.rules.employee"
              >
                <el-select
                  v-model="scope.row.employee"
                  placeholder="选择律师"
                  clearable
                  size="small"
                  value-key="employee"
                >
                  <el-option
                    v-for="item in employeeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="岗位" align="center">
            <template slot-scope="scope">
              <el-form-item
                :prop="'params.' + scope.$index + '.post'"
                :rules="lawyerForm.rules.post"
              >
                <el-select
                  v-model="scope.row.post"
                  placeholder="请选择岗位"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="p in positions"
                    :key="p.value"
                    :label="p.label"
                    :value="p.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80px" align="center">
            <template slot-scope="scope">
              <el-form-item>
                <el-button
                  type="danger"
                  size="mini"
                  circle
                  icon="el-icon-delete"
                  @click="handleItemDelete(scope)"
                ></el-button>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <div slot="footer">
        <el-button
          type="info"
          size="mini"
          icon="el-icon-circle-close"
          @click="dlgLawyerVisible = false"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCustomers,
  addCustomer,
  updateCustomer,
  delCustomer,
} from "@/api/customer";
import { addCasePerson, updateCasePerson, delCasePerson } from "@/api/customer";
import {
  addCaseLawyer,
  delCaseLawyer,
  updateCaseLawyers,
  hanzi2pinyin
} from "@/api/customer";
import { getCaseCategory } from "@/api/index";
import { getEmployeeList } from "@/api/employee";
import { positions } from "@/utils/const";

import Pagination from "@/components/Pagination";

const defaultForm = {
  id: undefined,
  name: "",
  gender: "",
  telephone: "",
  id_card: "",
  case_category: undefined,
  address: "",
  case_name: "",
  help_code: "",
};

const defaultPerson = {
  id: undefined,
  name: "",
  gender: "",
  telephone: "",
  id_card: "",
  customer: undefined,
};

const defaultLawyer = {
  id: undefined,
  employee: "",
  post: "",
  customer: null,
};

export default {
  name: "Customer",
  data() {
    // 验证手机号的规则
    const checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的手机号"));
    };

    return {
      customerForm: Object.assign({}, defaultForm),
      customerFormRules: {
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 1,
            max: 24,
            message: "长度在 1 到 30 个字符",
            trigger: "blur",
          },
        ],
        telephone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      genders: [
        {
          value: "男",
          label: "男",
        },
        {
          value: "女",
          label: "女",
        },
      ],
      // 客户信息
      dialogVisible: false,
      dialogType: "new",
      customerList: [],
      category: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        name: undefined,
      },
      // 相关人员
      dlgPersonVisible: false,
      dlgPersonType: "new",
      personForm: Object.assign({}, defaultPerson),
      customer: null,
      personFormRules: {
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 1,
            max: 24,
            message: "长度在 1 到 30 个字符",
            trigger: "blur",
          },
        ],
        telephone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        case_name: [
          { required: true, message: "请输入案件名称", trigger: "blur" },
        ],
      },
      // 负责律师
      dlgLawyerVisible: false,
      dlgLawyerType: "new",
      employeeList: [],

      lawyerForm: {
        params: [],
        rules: {
          employee: [
            {
              required: true,
              message: "请选择律师",
              trigger: ["blur", "change"],
            },
          ],
          post: [
            {
              required: true,
              message: "请选择岗位",
              trigger: ["blur", "change"],
            },
          ],
        },
      },

      positions: positions,
    };
  },
  components: {
    Pagination,
  },
  created() {
    this.getCustomers();
    this.getEmployees();
    this.getCaseCategory();
  },
  methods: {
    getHanzi2Pinyin() {
      const params = {
        name: this.customerForm.name,
      };
      hanzi2pinyin(params).then((res) => {
        this.customerForm.help_code = res.help_code;
      });
    },

    // 客户列表
    getCustomers() {
      this.listLoading = true;
      getCustomers(this.listQuery)
        .then((res) => {
          console.log(res);

          this.total = res.count;
          this.customerList = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取客户数据失败");
          this.listLoading = false;
        });
    },
    // 员工列表
    getEmployees() {
      getEmployeeList()
        .then((res) => {
          this.employeeList = res;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取员工信息失败");
        });
    },
    getCaseCategory() {
      getCaseCategory()
        .then((res) => {
          this.category = res;
        })
        .catch((error) => {
          this.$message.error("获取案件类型失败");
        });
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getCustomers();
    },
    // 增加客户
    handleAddCustomer() {
      this.customerForm = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.customerFormRef.clearValidate();
      });
    },
    // 修改客户
    handleEdit(scope) {
      this.customerForm = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["customerFormRef"].clearValidate();
      });
    },
    // 删除客户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该客户吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delCustomer(row.id);

          this.customerList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("客户信息删除失败!");
        });
    },
    // 相关人员添加
    handlePerson(customerInfo) {
      this.personForm = Object.assign({}, defaultPerson);
      this.personForm.customer = customerInfo.id;
      this.customer = customerInfo;
      this.dlgPersonType = "new";
      this.dlgPersonVisible = true;

      this.$nextTick(() => {
        this.$refs.personFormRef.clearValidate();
      });
    },
    // 相关人员修改
    handlePersonEdit(customerInfo, personInfo) {
      this.personForm = Object.assign({}, personInfo);
      this.dlgPersonType = "edit";
      this.customer = customerInfo;
      this.dlgPersonVisible = true;
      this.$nextTick(() => {
        this.$refs["personFormRef"].clearValidate();
      });
    },
    // 相关人员删除
    handlePersonDelete(customerInfo, { $index, row }) {
      this.customer = customerInfo;
      this.$confirm("确定要删除相关人员信息吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delCasePerson(row.id);

          this.customer.persons.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 相关人员保存
    SavePerson(flag) {
      this.$refs.personFormRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dlgPersonType === "edit";
        if (isEdit) {
          const res = await updateCasePerson(this.personForm);
          console.log(isEdit, res);
          const index = this.customer.persons.findIndex((v) => v.id === res.id);
          this.customer.persons.splice(index, 1, res);
        } else {
          const res = await addCasePerson(this.personForm);
          const { id } = res;
          if (id > 0) {
            this.customer.persons.push(res);
          }
        }

        const { name, telephone, id_card } = this.personForm;

        // 保存退出
        if (!flag) {
          this.dlgPersonVisible = false;
        } else {
          this.$refs.personFormRef.resetFields();
        }

        this.$notify({
          title: "相关人员操作成功",
          dangerouslyUseHTMLString: true,
          message: `
              <div>姓名: ${name}</div>
              <div>手机号: ${telephone}</div>
              <div>身份证: ${id_card}</div>
            `,
          type: "success",
        });
      });
    },
    // 保存操作
    async SaveCustomer() {
      this.$refs.customerFormRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        if (isEdit) {
          const res = await updateCustomer(this.customerForm);
          console.log(isEdit, res);
          const index = this.customerList.findIndex((v) => v.id === res.id);
          this.customerList.splice(index, 1, res);
        } else {
          const res = await addCustomer(this.customerForm);
          const { id } = res;
          if (id > 0) {
            this.getCustomers();
          }
        }

        const { name, telephone, id_card, case_name } = this.customerForm;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>姓名: ${name}</div>
              <div>手机号: ${telephone}</div>
              <div>身份证: ${id_card}</div>
              <div>案件名称: ${case_name}</div>
            `,
          type: "success",
        });
      });
    },
    // 负责律师添加
    handleLawyer(customer) {
      this.customer = customer;
      if (customer.lawyers.length > 0) {
        this.dlgLawyerType = "edit";
      } else {
        this.dlgLawyerType = "new";
      }

      this.dlgLawyerVisible = true;
      this.lawyerForm.params = [];
      this.lawyerForm.params = customer.lawyers;

      this.$nextTick(() => {
        this.$refs.lawyerFormRef.clearValidate();
      });
    },
    // 增加律师
    handleLawyerAdd() {
      let lawyer = Object.assign({}, defaultLawyer);
      lawyer.customer = this.customer.id;
      this.lawyerForm.params.push(lawyer);
    },
    // 负责律师保存
    SaveLawyer(flag) {
      this.$refs.lawyerFormRef.validate(async (valid) => {
        if (!valid) return;

        let res = null;

        if (this.dlgLawyerType == "new") {
          res = await addCaseLawyer(this.lawyerForm.params);
        } else {
          res = await updateCaseLawyers(this.lawyerForm.params);
        }

        console.log("res:", res);
        this.dlgLawyerVisible = false;
        if (res.length > 0) {
          this.$message.success("分配律师成功!");
        } else {
          this.$message.success("分配律师失败!");
        }
        this.getCustomers();
      });
    },
    delLawyer(customerInfo, index, item) {
      console.log(item, index, customerInfo);
      this.customer = customerInfo;
      if (item.id == undefined || item.id == null) {
        this.customer.lawyers.splice(index, 1);
        return;
      }
      delCaseLawyer(item.id)
        .then((res) => {
          console.log(res);
          this.customer.lawyers.splice(index, 1);
        })
        .catch((error) => {
          console.log(error.message);
        });
    },
    handleItemDelete(scope) {
      console.log(scope);
      let row = scope.row;

      if (row.id == undefined || row.id == null) {
        this.lawyerForm.params.splice(scope.$index, 1);
      } else if (row.id > 0) {
        this.$confirm("确定要删除相关人员信息吗?", "删除提示：", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            try {
              const res = await delCaseLawyer(row.id);
              this.lawyerForm.params.splice(scope.$index, 1);
              this.$message({ type: "success", message: "律师删除成功!" });
            } catch (err) {
              this.$message.error("律师删除失败!");
            }
          })
          .catch((error) => {});
      }
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  // .box-card{
  //   margin-top: 30px;
  // }
  .el-table {
    margin-top: 10px;
    width: 100%;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
  .el-select {
    width: 100%;
  }
  .el-tag {
    margin-right: 15px;
  }
  .lawyer-title {
    margin-left: 5px;
    height: 32px;
    line-height: 32px;
    vertical-align: center;
  }
  .el-form-item {
    margin-bottom: 15px;
  }
}
</style>